package patrol.mobile.com.mobilepatrol.activity.security.emergency;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.ScanActivity;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.activity.security.ConsTitles;
import patrol.mobile.com.mobilepatrol.api.MyHandler;
import patrol.mobile.com.mobilepatrol.bean.ProtectListBean;
import patrol.mobile.com.mobilepatrol.test.GsonTest;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.ScanUtils;
import patrol.mobile.com.mobilepatrol.utils.ToastUtils;

/**
 * Created by fuzhen.li on 2018/11/3.
 */
public class EmergencySignScanActivity extends BaseActivity implements QRCodeView.Delegate {

    @BindView(R.id.iv_scan)
    ImageView ivScan;
    @BindView(R.id.btn_scan)
    Button btnScan;
    @BindView(R.id.pBar)
    ProgressBar pBar;


    private static final String TAG = EmergencySignScanActivity.class.getSimpleName();

    private QRCodeView mQRCodeView;


    @Override
    protected void onStart() {
        super.onStart();
        // 打开后置摄像头开始预览，但是并未开始识别
        //todo  先注销
        mQRCodeView.startCamera();
        //显示扫描框
        mQRCodeView.showScanRect();
        //开始扫描
        mQRCodeView.startSpot();
    }

    @Override
    protected void onStop() {
        //关闭摄像头预览，并且隐藏扫描框
        mQRCodeView.stopCamera();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        mQRCodeView.onDestroy();
        if (myThread.isAlive()) {
            myThread.stop();
            myThread = null;
        }

    }

    //震动
    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        //startActivity(new Intent(EmergencySignScanActivity.this, GsonTest.class));
//        Log.i(TAG, "result:" + result);
//        Toast.makeText(this, result, Toast.LENGTH_SHORT).show();

        String identity = result;//    identity=622323198907046811
        String[] splits = identity.split("=");
        String id = splits[1];
        Intent intent = new Intent(EmergencySignScanActivity.this, EmergencyPeopleInfoActivity.class);
        intent.putExtra("holderId", id);
        startActivity(intent);

        vibrate();
        mQRCodeView.startSpot();

        finish();



    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Toast.makeText(EmergencySignScanActivity.this, "打开相机出错", Toast.LENGTH_SHORT).show();
        Log.e(TAG, "打开相机出错");
        finish();
    }


    @Override
    public void initView() {
        super.initView();
        mQRCodeView = (ZXingView) findViewById(R.id.zxingview);
        //设置扫描二维码的代理
        mQRCodeView.setDelegate(this);
    }

    private MyHandler mHandler = new MyHandler();

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    class MyHandler extends android.os.Handler {


        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String identity = (String) msg.obj;//    identity=622323198907046811
            String[] splits = identity.split("=");
            String id = splits[1];
            Intent intent = new Intent(EmergencySignScanActivity.this, EmergencyPeopleInfoActivity.class);
            intent.putExtra("holderId", id);
            startActivity(intent);
            finish();
        }
    }


    private List<ProtectListBean> protectListBeanList = new ArrayList<>();

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_emergency_signin_scan;
    }

    @Override
    public void setListener() {
        pBar.setVisibility(View.VISIBLE);
       // myThread.start();

//
//        mHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                String id = ScanUtils.recogQRcode(ivScan);
//                if (!TextUtils.isEmpty(id)) {
//                    pBar.setVisibility(View.GONE);
//                    ToastUtils.showToast(id);
//                    Intent intent = new Intent(EmergencySignScanActivity.this, EmergencyPackageSignInActivity.class);
//                    intent.putExtra("sigin", (ArrayList) protectListBeanList);
//                    startActivity(intent);
//                    finish();
//                }
//            }
//        },2000);


    }

    private MyThread myThread = new MyThread();


    class MyThread extends Thread {
        @Override
        public void run() {
            super.run();
            decodeBarcodeRGB(BitmapFactory.decodeResource(EmergencySignScanActivity.this.getResources(), R.mipmap.person_scan));
        }
    }

    @Override
    public void initTitle() {
        super.initTitle();
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(EmergencySignScanActivity.this, true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText(ConsTitles.EMERGENCY_SIGN_IN_SCAN);

    }

    @Override
    public void initData() {
        super.initData();

        Intent intent = getIntent();
        if (intent != null) {
            protectListBeanList = (List<ProtectListBean>) intent.getSerializableExtra("sigin");
        }

    }

    @OnClick({R.id.btn_scan})
    public void onTVClick(View v) {
        switch (v.getId()) {
            case R.id.btn_scan:
//                pBar.setVisibility(View.VISIBLE);
//                String result = ScanUtils.recogQRcode(ivScan);
//                if (!TextUtils.isEmpty(result)){
//                    pBar.setVisibility(View.GONE);
//                    ToastUtils.showToast(result);
//                }

                break;
        }
    }


    /**
     * 解析二维码 （使用解析RGB编码数据的方式）
     *
     * @param barcode
     * @return
     */
    public Result decodeBarcodeRGB(Bitmap barcode) {
        int width = barcode.getWidth();
        int height = barcode.getHeight();
        int[] data = new int[width * height];
        barcode.getPixels(data, 0, width, 0, 0, width, height);
        RGBLuminanceSource source = new RGBLuminanceSource(barcode);
        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        Result result = null;
        try {
            result = reader.decode(bitmap1);
            Message message = new Message();
            message.obj = result.getText();
            mHandler.sendMessage(message);
        } catch (Exception e) {
            result = null;
            e.printStackTrace();
        }
        barcode.recycle();
        barcode = null;

        return result;
    }

}
